<template>
  <transition name="preview-fade">
    <div
      v-if="previewStore.visible"
      class="preview-modal-overlay"
      @click.self="handleClose"
    >
      <div class="preview-modal">
        <div class="preview-header">
          <div>
            <p class="preview-title">文件预览</p>
            <p class="preview-subtitle">{{ previewStore.displayName }}</p>
          </div>
          <button class="icon-btn" @click="handleClose">×</button>
        </div>

        <div class="preview-toolbar">
          <div class="toolbar-left">
            <span class="file-tag">{{ fileExtension.toUpperCase() || '未知' }}</span>
            <span class="preview-tips" v-if="isOffice">Office 文件需要先点击“在线预览”</span>
          </div>
          <div class="toolbar-right">
            <button class="btn" @click="downloadFile">下载文件</button>
            <button v-if="isOffice && !showOfficeViewer" class="btn ghost" @click="toggleOfficeViewer">
              在线预览
            </button>
          </div>
        </div>

        <div class="preview-body">
          <div v-if="isPdf" class="preview-pdf">
            <div v-if="binaryLoading" class="loading-state">加载中...</div>
            <div v-else-if="binaryError" class="error-state">
              {{ binaryError }}
              <button class="btn ghost" @click="loadBinaryContent">重试</button>
            </div>
            <iframe
              v-else
              :src="binaryUrl || previewStore.previewUrl"
              frameborder="0"
              class="preview-iframe"
            ></iframe>
          </div>

          <img
            v-else-if="isImage"
            :src="binaryUrl || previewStore.previewUrl"
            class="preview-image"
            alt="文件预览"
          />

          <audio
            v-else-if="isAudio"
            :src="previewStore.previewUrl"
            controls
            controlslist="nodownload"
            class="preview-audio"
          ></audio>

          <video
            v-else-if="isVideo"
            :src="previewStore.previewUrl"
            controls
            controlslist="nodownload"
            class="preview-video"
          ></video>

          <div v-else-if="isText" class="preview-text-wrapper">
            <div v-if="textLoading" class="loading-state">加载中...</div>
            <div v-else-if="textError" class="error-state">{{ textError }}</div>
            <pre v-else class="preview-text">{{ textContent }}</pre>
          </div>

          <div v-else-if="isOffice" class="office-preview">
            <iframe
              v-if="showOfficeViewer"
              :src="officeViewerUrl"
              frameborder="0"
              class="preview-iframe"
            ></iframe>
            <p v-else class="preview-helper">
              此文件为 Office 文档，请点击上方“在线预览”或下载后使用 Office 软件打开。
            </p>
          </div>

          <div v-else class="preview-unsupported">
             <p>暂不支持该格式的在线预览。</p>
             <button class="btn" @click="downloadFile">立即下载</button>
          </div>
        </div>
      </div>
    </div>
  </transition>
</template>

<script setup>
import { computed, onUnmounted, ref, watch } from 'vue';
import { usePreviewStore } from '@/stores/previewStore';

const previewStore = usePreviewStore();
const textContent = ref('');
const textLoading = ref(false);
const textError = ref('');
const showOfficeViewer = ref(false);
const binaryUrl = ref('');
const binaryLoading = ref(false);
const binaryError = ref('');

const AUDIO_EXTENSIONS = ['mp3', 'wav', 'ogg', 'aac', 'm4a', 'flac'];
const VIDEO_EXTENSIONS = ['mp4', 'webm', 'mov', 'avi'];
const IMAGE_EXTENSIONS = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'];
const PDF_EXTENSIONS = ['pdf'];
const TEXT_EXTENSIONS = ['txt', 'json', 'xml', 'csv', 'log', 'md'];
const OFFICE_EXTENSIONS = ['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx'];

const fileExtension = computed(() => previewStore.fileExtension || '');

const isPdf = computed(() =>
  PDF_EXTENSIONS.includes(fileExtension.value)
);
const isImage = computed(() =>
  IMAGE_EXTENSIONS.includes(fileExtension.value)
);
const isAudio = computed(() =>
  AUDIO_EXTENSIONS.includes(fileExtension.value)
);
const isVideo = computed(() =>
  VIDEO_EXTENSIONS.includes(fileExtension.value)
);
const isText = computed(() =>
  TEXT_EXTENSIONS.includes(fileExtension.value)
);
const isOffice = computed(() =>
  OFFICE_EXTENSIONS.includes(fileExtension.value)
);

const officeViewerUrl = computed(() => {
  if (!previewStore.previewUrl) return '';
  const encoded = encodeURIComponent(previewStore.previewUrl);
  return `https://view.officeapps.live.com/op/embed.aspx?src=${encoded}`;
});

const shouldLoadBinary = computed(() => isPdf.value);

const releaseBinaryUrl = () => {
  if (binaryUrl.value) {
    URL.revokeObjectURL(binaryUrl.value);
    binaryUrl.value = '';
  }
};

const loadBinaryContent = async () => {
  if (!previewStore.previewUrl || !shouldLoadBinary.value) return;

  binaryLoading.value = true;
  binaryError.value = '';
  releaseBinaryUrl();

  try {
    const response = await fetch(previewStore.previewUrl);
    if (!response.ok) {
      throw new Error('加载文件失败');
    }
    const blob = await response.blob();
    binaryUrl.value = URL.createObjectURL(blob);
  } catch (error) {
    console.error('加载文件失败:', error);
    binaryError.value = error.message || '加载文件失败';
  } finally {
    binaryLoading.value = false;
  }
};

const loadTextContent = async () => {
  if (!previewStore.previewUrl) return;

  textLoading.value = true;
  textError.value = '';
  textContent.value = '';

  try {
    const response = await fetch(previewStore.previewUrl);
    if (!response.ok) {
      throw new Error('加载文本失败');
    }
    textContent.value = await response.text();
  } catch (error) {
    console.error('加载文本失败:', error);
    textError.value = error.message || '加载文本失败';
  } finally {
    textLoading.value = false;
  }
};

watch(
  () => previewStore.visible,
  (visible) => {
    document.body.style.overflow = visible ? 'hidden' : '';
    if (!visible) {
      textContent.value = '';
      textError.value = '';
      showOfficeViewer.value = false;
      binaryError.value = '';
      binaryLoading.value = false;
      releaseBinaryUrl();
    }
  }
);

watch(
  () => previewStore.visible && isText.value,
  (shouldLoad) => {
    if (shouldLoad) {
      loadTextContent();
    }
  }
);

watch(
  () => previewStore.previewUrl,
  () => {
    if (previewStore.visible && shouldLoadBinary.value) {
      loadBinaryContent();
    } else {
      releaseBinaryUrl();
      binaryError.value = '';
      binaryLoading.value = false;
    }
  }
);

watch(
  shouldLoadBinary,
  (need) => {
    if (!previewStore.visible) return;
    if (need) {
      loadBinaryContent();
    } else {
      releaseBinaryUrl();
      binaryError.value = '';
      binaryLoading.value = false;
    }
  }
);

const handleClose = () => {
  previewStore.closePreview();
};

const downloadFile = () => {
  if (!previewStore.downloadUrl) return;
  window.open(previewStore.downloadUrl, '_blank');
};

const toggleOfficeViewer = () => {
  showOfficeViewer.value = true;
};

onUnmounted(() => {
  document.body.style.overflow = '';
  releaseBinaryUrl();
});
</script>

<style scoped>
.preview-modal-overlay {
  position: fixed;
  inset: 0;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 2000;
  padding: 20px;
}

.preview-modal {
  width: min(1200px, 100%);
  height: min(90vh, 900px);
  background: #fff;
  border-radius: 16px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.2);
}

.preview-header {
  display: flex;
  justify-content: space-between;
  padding: 16px 24px;
  border-bottom: 1px solid #f0f0f0;
}

.preview-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.preview-subtitle {
  font-size: 14px;
  color: #666;
}

.icon-btn {
  border: none;
  background: #f5f5f5;
  border-radius: 50%;
  width: 32px;
  height: 32px;
  font-size: 18px;
  cursor: pointer;
}

.preview-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 24px;
  border-bottom: 1px solid #f0f0f0;
  background: #fafafa;
}

.toolbar-left {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 14px;
  color: #666;
}

.file-tag {
  padding: 2px 8px;
  border-radius: 4px;
  background: #eef2ff;
  color: #4c51bf;
  font-weight: 600;
  font-size: 12px;
}

.preview-tips {
  color: #d97706;
}

.toolbar-right {
  display: flex;
  gap: 12px;
}

.btn {
  padding: 8px 16px;
  border-radius: 6px;
  border: none;
  background: #6366f1;
  color: #fff;
  cursor: pointer;
  font-size: 14px;
}

.btn.ghost {
  background: transparent;
  color: #6366f1;
  border: 1px solid #c7d2fe;
}

.preview-body {
  flex: 1;
  padding: 16px 24px 24px;
  background: #f9fafb;
}

.preview-pdf {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.preview-pdf .preview-iframe {
  flex: 1;
}

.preview-iframe,
.preview-video {
  width: 100%;
  height: 100%;
  border-radius: 12px;
  background: #fff;
}

.preview-image {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
  border-radius: 12px;
  background: #fff;
  display: block;
  margin: 0 auto;
}

.preview-audio {
  width: 100%;
  margin-top: 120px;
}

.preview-text-wrapper {
  width: 100%;
  height: 100%;
  background: #fff;
  border-radius: 12px;
  padding: 16px;
  overflow: auto;
  border: 1px solid #e5e7eb;
}

.preview-text {
  white-space: pre-wrap;
  word-break: break-word;
  font-family: 'Courier New', monospace;
  font-size: 14px;
  color: #1f2937;
}

.preview-helper,
.preview-unsupported p {
  color: #4b5563;
  text-align: center;
  margin-bottom: 16px;
}

.preview-unsupported {
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  gap: 16px;
}

.loading-state,
.error-state {
  color: #4b5563;
  text-align: center;
  padding: 40px 0;
}

.error-state {
  color: #dc2626;
}

.preview-fade-enter-active,
.preview-fade-leave-active {
  transition: opacity 0.2s ease;
}

.preview-fade-enter-from,
.preview-fade-leave-to {
  opacity: 0;
}
</style>

